  <th:block layout:fragment="scripts">
        <script>
            let clients = []; // 存储客户数据
            
            document.addEventListener('DOMContentLoaded', function() {
                loadClients();
                
                // 设置表单提交事件
                document.getElementById('clientForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    saveClient();
                });
                
                // 设置搜索和筛选事件
                document.getElementById('searchClient').addEventListener('input', filterClients);
                document.getElementById('filterStatus').addEventListener('change', filterClients);
                document.getElementById('filterSource').addEventListener('change', filterClients);
            });

            // 从服务器加载客户列表
            function loadClients() {
                fetch('/api/sales/clients/list')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            clients = result.data;
                            renderClients();
                        } else {
                            console.error('加载客户列表失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载客户列表失败:', error));
            }
            
            // 渲染客户列表
            function renderClients() {
                const table = document.getElementById('clients-table');
                const tbody = table.querySelector('tbody');
                tbody.innerHTML = '';
                
                if (clients.length === 0) {
                    const emptyRow = document.createElement('tr');
                    emptyRow.innerHTML = '<td colspan="8" class="text-center">没有找到客户数据</td>';
                    tbody.appendChild(emptyRow);
                    return;
                }
                
                clients.forEach(client => {
                    const row = document.createElement('tr');
                    
                    // 设置状态样式
                    let statusClass = '';
                    switch(client.status) {
                        case 'POTENTIAL': statusClass = 'badge-warning'; break;
                        case 'ACTIVE': statusClass = 'badge-success'; break;
                        case 'INACTIVE': statusClass = 'badge-secondary'; break;
                        case 'LOST': statusClass = 'badge-danger'; break;
                    }
                    
                    // 获取状态对应的显示文本
                    const statusText = {
                        'POTENTIAL': '潜在客户',
                        'ACTIVE': '活跃客户',
                        'INACTIVE': '非活跃',
                        'LOST': '流失客户'
                    }[client.status] || client.status;
                    
                    row.innerHTML = `
                        <td>${client.id}</td>
                        <td>${client.name}</td>
                        <td>${client.contact || '-'}</td>
                        <td>${client.phone || '-'}</td>
                        <td>${client.email || '-'}</td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>${client.source || '-'}</td>
                        <td>
                            <button class="btn btn-sm btn-info" onclick="viewClient(${client.id})">查看</button>
                            <button class="btn btn-sm btn-primary" onclick="editClient(${client.id})">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteClient(${client.id})">删除</button>
                        </td>
                    `;
                    
                    tbody.appendChild(row);
                });
            }

            function showAddClientModal() {
                document.getElementById('modalTitle').textContent = '添加客户';
                document.getElementById('clientForm').reset();
                
                // 移除可能存在的客户ID
                document.getElementById('clientForm').removeAttribute('data-id');
                
                // 显示模态框
                document.getElementById('clientModal').style.display = 'block';
            }

            function closeModal() {
                document.getElementById('clientModal').style.display = 'none';
            }

            function editClient(clientId) {
                document.getElementById('modalTitle').textContent = '编辑客户';
                
                // 获取客户详情
                fetch(`/api/sales/clients/${clientId}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const client = result.data;
                            
                            // 填充表单
                            document.getElementById('clientName').value = client.name;
                            document.getElementById('clientContact').value = client.contact || '';
                            document.getElementById('clientPhone').value = client.phone || '';
                            document.getElementById('clientEmail').value = client.email || '';
                            document.getElementById('clientStatus').value = client.status;
                            document.getElementById('clientSource').value = client.source || '';
                            document.getElementById('clientAddress').value = client.address || '';
                            document.getElementById('clientNotes').value = client.notes || '';
                            
                            // 设置表单客户ID用于保存
                            document.getElementById('clientForm').setAttribute('data-id', client.id);
                            
                            // 显示模态框
                            document.getElementById('clientModal').style.display = 'block';
                        } else {
                            console.error('加载客户详情失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载客户详情失败:', error));
            }
            
            function viewClient(clientId) {
                // 跳转到客户详情页面
                window.location.href = `/sales/clients/${clientId}`;
            }
            
            function deleteClient(clientId) {
                if (confirm('确定要删除这个客户吗？相关联的销售记录也会一并删除。')) {
                    fetch(`/api/sales/clients/delete/${clientId}`, {
                        method: 'DELETE'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            // 刷新客户列表
                            loadClients();
                        } else {
                            alert('删除客户失败: ' + result.message);
                        }
                    })
                    .catch(error => {
                        console.error('删除客户失败:', error);
                        alert('系统错误，请稍后重试');
                    });
                }
            }
            
            function saveClient() {
                const clientForm = document.getElementById('clientForm');
                const clientId = clientForm.getAttribute('data-id');
                const isEdit = !!clientId;
                
                const clientData = {
                    name: document.getElementById('clientName').value,
                    contact: document.getElementById('clientContact').value,
                    phone: document.getElementById('clientPhone').value,
                    email: document.getElementById('clientEmail').value,
                    status: document.getElementById('clientStatus').value,
                    source: document.getElementById('clientSource').value,
                    address: document.getElementById('clientAddress').value,
                    notes: document.getElementById('clientNotes').value
                };
                
                if (isEdit) {
                    clientData.id = parseInt(clientId);
                }
                
                const url = isEdit ? '/api/sales/clients/update' : '/api/sales/clients/add';
                const method = isEdit ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(clientData)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        // 关闭模态框，重新加载客户列表
                        closeModal();
                        loadClients();
                    } else {
                        alert('保存客户失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('保存客户失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
            
            function filterClients() {
                const searchTerm = document.getElementById('searchClient').value.toLowerCase();
                const statusFilter = document.getElementById('filterStatus').value;
                const sourceFilter = document.getElementById('filterSource').value;
                
                // 构建过滤条件
                const params = new URLSearchParams();
                if (searchTerm) params.append('search', searchTerm);
                if (statusFilter) params.append('status', statusFilter);
                if (sourceFilter) params.append('source', sourceFilter);
                
                // 发送带参数的请求
                fetch(`/api/sales/clients/list?${params.toString()}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            clients = result.data;
                            renderClients();
                        } else {
                            console.error('筛选客户失败:', result.message);
                        }
                    })
                    .catch(error => console.error('筛选客户失败:', error));
            }
            
            function resetFilters() {
                document.getElementById('searchClient').value = '';
                document.getElementById('filterStatus').value = '';
                document.getElementById('filterSource').value = '';
                loadClients(); // 重新加载所有客户
            }
            
            // 导出客户数据
            function exportClientData() {
                // 构建当前筛选条件
                const searchTerm = document.getElementById('searchClient').value.toLowerCase();
                const statusFilter = document.getElementById('filterStatus').value;
                const sourceFilter = document.getElementById('filterSource').value;
                
                const params = new URLSearchParams();
                if (searchTerm) params.append('search', searchTerm);
                if (statusFilter) params.append('status', statusFilter);
                if (sourceFilter) params.append('source', sourceFilter);
                
                // 打开导出链接（下载文件）
                window.location.href = `/api/sales/clients/export?${params.toString()}`;
            }
            
            // 导入客户数据
            function importClientData() {
                const fileInput = document.getElementById('importFile');
                if (!fileInput.files || fileInput.files.length === 0) {
                    alert('请选择要导入的文件');
                    return;
                }
                
                const formData = new FormData();
                formData.append('file', fileInput.files[0]);
                
                fetch('/api/sales/clients/import', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        alert(`成功导入 ${result.data} 条客户数据`);
                        loadClients(); // 重新加载数据
                        closeImportModal();
                    } else {
                        alert('导入失败: ' + result.message);
                    }
                })
                .catch(error => {
                    console.error('导入失败:', error);
                    alert('系统错误，请稍后重试');
                });
            }
            
            function showImportModal() {
                document.getElementById('importModal').style.display = 'block';
            }
            
            function closeImportModal() {
                document.getElementById('importModal').style.display = 'none';
                document.getElementById('importFile').value = ''; // 清空文件输入
            }
        </script>
    </th:block> 